package persistent.prestige.console.task.w04;

import java.io.Serializable;
import java.nio.ByteBuffer;

/**
 * 
 * 这里为了简单起见，没有使用装饰模式，，继承在 ByteBuffer,然后重写其方法，为了节省时间，直接用unwap方法返回其内部的ByteBuffer
 * 
 * @author dingwei2
 *
 */
@SuppressWarnings("serial")
public class DirectByteBuf implements Serializable, Comparable<DirectByteBuf> {

	/**
	 * 内部的ByteBuffer
	 */
	private ByteBuffer innerBuf;

	private int capacity;
	
	private boolean cache;
	
	
	@Override
	public int compareTo(DirectByteBuf o) {
		if(o == null ) return 1;//如果为空，则表示当前比这个大
		
		if(this.capacity == o.capacity ) return 0;
		
		return  this.capacity > o.capacity ? 1 : -1;
	}
	

	protected DirectByteBuf(int capacity) {
		this.capacity = capacity;
	}

	protected DirectByteBuf(ByteBuffer innerBuf, boolean cache) {
		if (innerBuf == null)
			throw new NullPointerException("DirectByteBuf buf must't null。");
		this.innerBuf = innerBuf;
		this.capacity = innerBuf.capacity();
		this.cache = cache;

	}

	public int capacity() {
		return capacity;
	}
	
	public void setCapacity(int capacity) {
		if(this.innerBuf != null) {
			throw new UnsupportedOperationException("该Buffer不支持该操作");
		}
		
		this.capacity = capacity;
	}

	public boolean isCache() {
		return cache;
	}
	
	public ByteBuffer unwap() {
		return innerBuf;
	}


	@Override
	public int hashCode() {
		if(innerBuf != null ) {
			return innerBuf.hashCode();
		}
		
		return (new Integer(this.capacity)).hashCode();
	}


	@Override
	public boolean equals(Object obj) {
		if(! (obj instanceof DirectByteBuf) ) {
			return false;
		}
		
		DirectByteBuf o = (DirectByteBuf)obj;
		if(innerBuf != null && o.unwap() != null  ) {
			return innerBuf.equals(o.unwap());
		}
		
		if(innerBuf == null && o.unwap() == null) {
			return this.capacity == o.capacity();
		}
		
		
		return false;
	}
	
	
	

}
